<template>
  <div class="tcm-encyclopedia-container">
    <div class="header">
      <h3>中医百科</h3>
    </div>

    <div class="search-bar-card">
      <el-input v-model="searchQuery" placeholder="搜索中医知识" prefix-icon="Search" />
    </div>

    <div class="categories-card">
      <h4>知识分类</h4>
      <div class="category-tags">
        <el-tag v-for="category in categories" :key="category.value"
          :type="selectedCategory === category.value ? 'success' : 'info'" effect="plain" round
          @click="selectCategory(category.value)">
          {{ category.label }}
        </el-tag>
      </div>
    </div>

    <div class="knowledge-list-card">
      <h4>中医知识列表</h4>
      <el-empty v-if="knowledgeList.length === 0" description="暂无相关知识"></el-empty>
      <el-card v-for="item in filteredKnowledgeList" :key="item.id" shadow="hover" class="knowledge-item-card"
        @click="goToDetail(item.id)">
        <template #header>
          <div class="card-header">
            <span>{{ item.title }}</span>
            <div class="actions">
              <el-icon @click.stop="toggleCollect(item)">
                <Star :class="{ 'is-collected': item.collected }" />
              </el-icon>
              <el-icon @click.stop="shareKnowledge(item)">
                <Share />
              </el-icon>
            </div>
          </div>
        </template>
        <div class="item-content">
          <p>{{ item.summary }}</p>
        </div>
      </el-card>
    </div>

  </div>
</template>

<script setup>
import { Share, Star } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
// 假设的API函数，待实际对接后端

const router = useRouter()

const searchQuery = ref('')
const selectedCategory = ref('all')
const categories = ref([
  { label: '全部', value: 'all' },
  { label: '体质养生', value: 'constitution' },
  { label: '中药方剂', value: 'herbal' },
  { label: '针灸推拿', value: 'acupuncture' },
  { label: '食疗养生', value: 'diet' },
])
const knowledgeList = ref([])

// 模拟数据，实际应从后端获取
const mockKnowledgeData = [
  // 皮肤病相关内容优先
  { id: 101, title: '痤疮的中医辨证与调理', summary: '痤疮多因湿热、血热、脾虚等引起，宜清热解毒、调理脾胃。', category: 'constitution', collected: false },
  { id: 102, title: '湿疹的饮食与护理建议', summary: '湿疹患者应忌辛辣刺激食物，多吃新鲜蔬果，保持皮肤清洁。', category: 'diet', collected: false },
  { id: 103, title: '皮肤屏障修复的中医思路', summary: '中医认为皮肤屏障损伤多与肺脾两虚、气血不足有关，宜健脾益气、养血润肤。', category: 'herbal', collected: false },
  { id: 104, title: '敏感肌的中医调理', summary: '敏感肌多因气血不足、卫外不固，宜补气养血、固表护肤。', category: 'constitution', collected: false },
  // 通用内容
  { id: 1, title: '气虚体质的调养秘籍', summary: '气虚体质者常感乏力，易疲劳。调养重在益气健脾。', category: 'constitution', collected: false },
  { id: 2, title: '常用中药材辨识与功效', summary: '了解黄芪、人参、当归等常用中药材的药性与应用。', category: 'herbal', collected: false },
  { id: 3, title: '艾灸疗法缓解颈椎不适', summary: '艾灸是中医传统疗法，对颈椎病有良好辅助治疗效果。', category: 'acupuncture', collected: false },
  { id: 4, title: '春季养肝食疗方', summary: '春季宜养肝，推荐多食用绿色蔬菜和酸味食物。', category: 'diet', collected: false },
  { id: 5, title: '湿热体质的症状与改善', summary: '湿热体质者易长痘、口苦，需清热利湿。', category: 'constitution', collected: false },
]

const filteredKnowledgeList = computed(() => {
  let filtered = knowledgeList.value
  if (selectedCategory.value !== 'all') {
    filtered = filtered.filter(item => item.category === selectedCategory.value)
  }
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.trim().toLowerCase()
    filtered = filtered.filter(item =>
      item.title.toLowerCase().includes(query) ||
      item.summary.toLowerCase().includes(query)
    )
  }
  return filtered
})

const fetchKnowledge = async () => {
  try {
    // 实际项目中应调用API：const res = await getTcmKnowledgeListApi();
    // 暂时使用模拟数据
    knowledgeList.value = mockKnowledgeData
    // categories.value = await getTcmCategoriesApi(); // 如果分类也从后端获取
  } catch (error) {
    console.error('获取中医知识失败:', error)
    ElMessage.error('获取中医知识失败')
  }
}

const selectCategory = (category) => {
  selectedCategory.value = category
}

const toggleCollect = async (item) => {
  try {
    // 实际项目中应调用API：await toggleCollectApi(item.id, !item.collected);
    item.collected = !item.collected
    ElMessage.success(item.collected ? '已收藏' : '已取消收藏')
  } catch (error) {
    ElMessage.error('收藏操作失败')
  }
}

const shareKnowledge = (item) => {
  // 模拟分享功能
  const shareText = `【中医百科】${item.title}: ${item.summary}`
  if (navigator.share) {
    navigator.share({
      title: item.title,
      text: shareText,
      url: window.location.href // 或者知识详情页的URL
    }).then(() => {
      ElMessage.success('分享成功！')
    }).catch((error) => {
      console.error('分享失败:', error)
      ElMessage.error('分享失败')
    })
  } else {
    // 兼容性处理，例如复制链接到剪贴板
    navigator.clipboard.writeText(shareText + ' ' + window.location.href)
      .then(() => {
        ElMessage.success('内容已复制到剪贴板！')
      })
      .catch((error) => {
        console.error('复制失败:', error)
        ElMessage.error('复制失败')
      })
  }
}

const goToDetail = (id) => {
  router.push(`/tcm-encyclopedia/${id}`)
}

onMounted(() => {
  fetchKnowledge()
})

</script>

<style scoped>
.tcm-encyclopedia-container {
  padding: 20px;
  background-color: #f7f8fa;
  min-height: calc(100vh - 50px);
  padding-bottom: 70px;
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.header h3 {
  font-size: 22px;
  color: #333;
}

.search-bar-card {
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 12px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.categories-card {
  background-color: #fff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.categories-card h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #2e8b57;
  font-size: 18px;
}

.category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.category-tags .el-tag {
  cursor: pointer;
  border-radius: 8px;
  /* 圆角 */
  padding: 8px 12px;
  font-size: 14px;
}

.category-tags .el-tag--success.is-plain {
  background-color: #e0ffe0;
  /* 选中时的浅绿色背景 */
  border-color: #2e8b57;
  color: #2e8b57;
}

.knowledge-list-card {
  background-color: #fff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
}

.knowledge-list-card h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #2e8b57;
  font-size: 18px;
}

.knowledge-item-card {
  margin-bottom: 15px;
  border-radius: 10px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
  cursor: pointer;
}

.knowledge-item-card:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: #333;
}

.card-header .actions .el-icon {
  font-size: 20px;
  margin-left: 10px;
  color: #999;
  cursor: pointer;
}

.card-header .actions .el-icon:hover {
  color: #2e8b57;
}

.card-header .actions .is-collected {
  color: #ff9800;
  /* 收藏的橙色 */
}

.item-content p {
  font-size: 14px;
  line-height: 1.6;
  color: #666;
}

/* 调整输入框圆角 */
:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #2e8b57 inset;
}
</style>